package com.onetech.adrewards.free.fragments;

import java.util.List;

import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.activities.BaseNewActivity;
import com.onetech.adrewards.free.adapters.ExchangeListAdapter;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.config.AppConfig.Cache;
import com.onetech.adrewards.free.customviews.LoadMoreListView;
import com.onetech.adrewards.free.fragments.v2.HomeFragment;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.models.GiftCardModel;
import com.onetech.adrewards.free.objects.ExchangeDTO;
import com.onetech.adrewards.free.objects.ExchangeGiftCarInfoDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.todddavies.components.progressbar.ProgressWheel;

public class ExchangeFragment extends BaseFragment {
	private ExchangeListAdapter mAdapter;
	private LoadGiftCardUserExchanged mLoadGiftCardUserExchange = null;
	private LoadExchangeGiftCardInfo mLoadExchangeGiftCardInfo = null;

	
	private ExchangeHandler mExchangeHandle = null;
	private View mExchangeNoHistoryView = null;
	public interface ExchangeHandler {
		public void reLoadFragment(boolean isReloadUserInfo,
				boolean isReloadExchangeHistory, boolean isCheckUserCoins);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.exchange_fragment_layout,
					container, false);
			initView();
			initListener();
		} else {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}

	private void initView() {
		
		mListView = (LoadMoreListView) mView.findViewById(R.id.myExchangeListView);
		mListView.setVisibility(View.GONE);
		mAdapter = new ExchangeListAdapter(getActivity());
		mListView.setAdapter(mAdapter);

		

		mExchangeNoHistoryView = (LinearLayout) mView
				.findViewById(R.id.exchange_no_history);
		showNoHistory(false);

		switchShowOrHideView(false, false);
		initNotFoundAndLoadingView();

		mProgress = (ProgressWheel) mView.findViewById(R.id.progressWheel);
		mProgress.setText("");
		mProgress.spin();

		mExchangeHandle = new ExchangeHandler() {
			@Override
			public void reLoadFragment(boolean isReloadUserInfo,
					boolean isReloadExchangeHistory, boolean isCheckUserCoins) {
				reLoadData(isReloadUserInfo, isReloadExchangeHistory,
						isCheckUserCoins);
			}
		};
	}

	private void initListener() {
		initRetryButtonListener();
		
		
		mListView.setOnLoadMoreListener(this);
		
	}

	private void showNoHistory(boolean isShowNoHistory) {
		mExchangeNoHistoryView.setVisibility(isShowNoHistory ? View.VISIBLE
				: View.GONE);
	}

	private void switchShowOrHideView(boolean isShowExchange,
			boolean isShowGetCoin) {
		
	}

	@Override
	public void onResume() {
		super.onResume();
		userCoins = ((BaseNewActivity)getActivity()).getUserCoins();
		if (mAdapter != null && mAdapter.getCount() < 1) {
			loadUserExchangedHistory();
		}
		checkUserCoins();
		
		
	}

	public void reLoadData(boolean isReloadUserInfo,
			boolean isReloadExchangeHistory, boolean isCheckUserCoins) {
		try {
			if (isReloadUserInfo) {
				((BaseNewActivity) getActivity()).getUserInfo();
			}
			if (isReloadExchangeHistory) {
				pageNo = 1;
				loadUserExchangedHistory();
			}
			if (isCheckUserCoins) {				
				loadExchangeGiftCardInfo();
			}			
			checkUserCoins();
		} catch (Exception e) {
		}
	}

	private void checkUserCoins() {
		try {			
			if (userCoins >= AppConfig.MIN_COIN_EXCHANGE) {
				switchShowOrHideView(true, false);
			} else {
				switchShowOrHideView(false, true);
			}
		} catch (Exception e) {
		}
	}

	private void loadUserExchangedHistory() {
		if (mLoadGiftCardUserExchange == null
				|| mLoadGiftCardUserExchange.getStatus() == Status.FINISHED) {
			mLoadGiftCardUserExchange = new LoadGiftCardUserExchanged();
			mLoadGiftCardUserExchange.execute();
		}
	}

	private void loadExchangeGiftCardInfo() {
		if (mLoadExchangeGiftCardInfo == null
				|| mLoadExchangeGiftCardInfo.getStatus() == Status.FINISHED) {
			mLoadExchangeGiftCardInfo = new LoadExchangeGiftCardInfo();
			mLoadExchangeGiftCardInfo.execute();
		}
	}

	@Override
	public void onLoadMore() {
		super.onLoadMore();
		loadUserExchangedHistory();
	}

	private class LoadGiftCardUserExchanged extends
			AsyncTask<Void, Void, List<ExchangeDTO>> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showNotFoundOrLoadingView(false, true);
			showNoHistory(false);
		}

		@Override
		protected List<ExchangeDTO> doInBackground(Void... params) {
			AdrewadsUtils.checkUId();
			return GiftCardModel.getInstance().getListHistoryUserExchanged(
					AppConfig.uId, String.valueOf(pageNo));
		}

		@Override
		protected void onPostExecute(List<ExchangeDTO> result) {
			super.onPostExecute(result);
			try {
				if (result != null) {
					if (result.size() < 1) {
						if (mAdapter.getCount() < 1) {
							showNotFoundOrLoadingView(false, false);
							showNoHistory(true);
							mListView.setVisibility(View.GONE);
						} else {
							showNoHistory(false);
							showNotFoundOrLoadingView(false, false);
							mListView.setVisibility(View.VISIBLE);
						}						
					} else {
						if (pageNo == 1) {
							mAdapter.updateAppList(result);
						} else {
							mAdapter.insertAppList(result);
						}
						pageNo++;
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				} else {
					if (mAdapter.getCount() < 1) {
						showNotFoundOrLoadingView(true, false);
						showNoHistory(false);
						mListView.setVisibility(View.GONE);
					} else {
						showNoHistory(false);
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				}
			} catch (Exception e) {
			}
			mListView.onLoadMoreComplete();
		}
	}

	private class LoadExchangeGiftCardInfo extends
			AsyncTask<Void, Void, ExchangeGiftCarInfoDTO> {

		@Override
		protected ExchangeGiftCarInfoDTO doInBackground(Void... params) {
			return GiftCardModel.getInstance().getExchangeGiftCardInfo();
		}

		@Override
		protected void onPostExecute(ExchangeGiftCarInfoDTO result) {
			super.onPostExecute(result);
			try {
				if (result != null) {
					userCoins=result.getTotal_coin();
					CommonModel.getInstance().setStore(Cache.ONE_TECH_USER_POINTS, String.valueOf(userCoins));
					checkUserCoins();
//					if (result.getTotal_coin() >= AppConfig.MIN_COIN_EXCHANGE) {
//						switchShowOrHideView(true, false);
////						ExchangeSelectDialog mExchangeSelectDialog = new ExchangeSelectDialog(
////								getActivity(), mExchangeHandle);
////						mExchangeSelectDialog.show();
//					} else {
//						switchShowOrHideView(false, true);
//					}
				}
			} catch (Exception e) {				
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.btnRetry:
			pageNo = 1;
			mListView.setVisibility(View.VISIBLE);
			showNotFoundOrLoadingView(false, true);
			loadUserExchangedHistory();
			break;
		
		case R.id.getCoinBtn:
			((HomeFragment) getParentFragment()).switchCurrentItem(1);
			break;
		default:
			super.onClick(v);
			break;
		}
	}
	
	@Override
    public void onStart() {
        super.onStart();
        try {
            mTracker.set(Fields.SCREEN_NAME, getActivity().getString(R.string.ExchangeFragment));            
            mTracker.send(MapBuilder.createAppView().build());            
		} catch (Exception e) {
		}
    }
	
}
